<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { showToast } from 'vant'
import { chat,message } from '@/api/chat'
import { getById } from '@/api/user'
import websocket from '@/utils/websocket'

const route = useRoute()
const userStore = useUserStore()
const messages = ref([])
const inputMessage = ref('')
const loading = ref(false)
const toUser = ref(null)


const sendMessage = async () => {
  if (!inputMessage.value.trim()) {
    return
  }

  try {
    loading.value = true
    // 构造消息请求对象
    const messageRequest = {
      content: inputMessage.value,
      userId: Number(route.params.id)
    }
    
    await chat(messageRequest)
    
    messages.value.push({
      content: inputMessage.value,
      isSelf: true,
      timestamp: new Date().toISOString()
    })
    
    inputMessage.value = ''
  } catch (error) {
    showToast('发送失败')
  } finally {
    loading.value = false
  }
}

const getUserInfo = async () => {
  const res = await getById(route.params.id)
  toUser.value = res.data
  console.log(toUser.value)
}

const getHistoryMessages = async () => {
  try {
    const res = await message(route.params.id)
    if (res.data?.message) {
      messages.value = res.data.message.map(msg => ({
        content: msg.content,
        isSelf: msg.sendId === userStore.id,
        timestamp: msg.createTime || new Date().toISOString()
      }))
    }
  } catch (error) {
    showToast('获取聊天记录失败')
  }
}

onMounted(() => {
  getUserInfo()
  getHistoryMessages()
  websocket.connect(userStore.id)
  websocket.ws.onmessage = (event) => {
    const data = JSON.parse(event.data)
    messages.value.push({
      content: data.content,
      isSelf: data.from === userStore.id,
      timestamp: data.timestamp
    })
  }
})

onUnmounted(() => {
  websocket.close()
})

const formatTime = (timestamp) => {
  return new Date(timestamp).toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}
</script>

<template>
  <div class="chat-page">
    <van-nav-bar 
      :title= "toUser?.username" 
      left-arrow 
      @click-left="$router.back()" 
    />
    
    <div class="message-list">
      <div 
        v-for="(msg, index) in messages" 
        :key="index"
        :class="['message-item', msg.isSelf ? 'self' : 'other']"
      >
        <img 
          :src="msg.isSelf ? userStore.avatar : toUser.avatar" 
          class="avatar"
        />
        <div class="message-content">
          <div class="message-text">{{ msg.content }}</div>
          <div class="message-time">{{ formatTime(msg.timestamp) }}</div>
        </div>
      </div>
    </div>

    <div class="input-area">
      <van-field
        v-model="inputMessage"
        placeholder="请输入消息"
        :border="false"
        @keyup.enter="sendMessage"
      >
        <template #button>
          <van-button 
            size="small" 
            type="primary" 
            @click="sendMessage"
          >
            发送
          </van-button>
        </template>
      </van-field>
    </div>
  </div>
</template>

<style scoped lang="scss">
.chat-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f7f7f7;

  .message-list {
    flex: 1;
    overflow-y: auto;
    padding: 16px;

    .message-item {
      display: flex;
      align-items: flex-start;
      margin-bottom: 16px;

      .avatar {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        margin: 0 8px;
      }

      .message-content {
        max-width: 70%;
        
        .message-text {
          padding: 12px;
          border-radius: 8px;
          word-break: break-all;
          margin-bottom: 4px;
        }

        .message-time {
          font-size: 12px;
          color: #999;
          text-align: right;
        }
      }

      &.self {
        flex-direction: row-reverse;

        .message-text {
          background: #007aff;
          color: #fff;
        }
      }

      &.other {
        .message-text {
          background: #fff;
          color: #333;
        }
      }
    }
  }

  .input-area {
    padding: 8px;
    background: #fff;
    border-top: 1px solid #eee;
  }
}
</style> 